import { defineComponent, h, ref, VNode } from "vue";
import { mountComponent } from "@/utils/component";

import PopupComp from "../popup/popup.vue";
import "./modal.less";

const PopupModal = defineComponent({
  setup(props, { expose }) {
    let showCallback: ((type: "confirm" | "cancel") => void) | undefined =
      undefined;

    let title = "";
    let showCancel = true;
    let cancelText = "";
    let confirmText = "";
    let width = "";

    const visible = ref(false);
    const content = ref<string | VNode>("");

    const cancelClcik = () => {
      visible.value = false;
      showCallback?.("cancel");
    };
    const confirmClcik = () => {
      visible.value = false;
      showCallback?.("confirm");
    };

    expose({
      show: (
        option: ModalOption,
        callback?: (type: "confirm" | "cancel") => void
      ) => {
        title = option.title || "提示";
        showCancel = option.showCancel === undefined ? true : option.showCancel;
        cancelText = option.cancelText || "取消";
        confirmText = option.confirmText || "确定";
        width = option.width || "80vw";
        content.value = option.content;
        visible.value = true;
        showCallback = callback;
      },
    });
    return () =>
      h(
        PopupComp,
        {
          modelValue: visible.value,
          style: { transform: "translateY(-60%)" },
        },
        () =>
          h("div", { class: "popup-modal", style: { width } }, [
            h("div", { class: "popup-modal-title", innerHTML: title }),
            h("div", { class: "popup-modal-content" }, content.value),
            h(
              "div",
              { class: "popup-modal-operate" },
              showCancel
                ? [
                    h("div", {
                      class: "popup-modal-cancel",
                      innerHTML: cancelText,
                      onClick: cancelClcik,
                    }),
                    h("div", {
                      class: "popup-modal-confirm",
                      innerHTML: confirmText,
                      onClick: confirmClcik,
                    }),
                  ]
                : [
                    h("div", {
                      class: "popup-modal-confirm",
                      innerHTML: confirmText,
                      onClick: confirmClcik,
                    }),
                  ]
            ),
          ])
      );
  },
});

export default {
  show: (option: ModalOption, confirm?: () => void, cancel?: () => void) => {
    const { instance, unmount } = mountComponent(PopupModal);
    (instance as any).show(option, (type: "confirm" | "cancel") => {
      type === "confirm" ? confirm?.() : cancel?.();
      unmount();
    });
  },
};

interface ModalOption {
  title?: string;
  content: string | VNode;
  showCancel?: boolean;
  cancelText?: string;
  confirmText?: string;
  width?: string;
}
